from .models import Navigation, Notice
from utils.serializers import CustomModelSerializer
from rest_framework import serializers


class NoticeSerializer(CustomModelSerializer):
    """
    系统公告-序列化器
    """

    read_ids = serializers.SerializerMethodField()

    class Meta:
        model = Notice
        fields = '__all__'
        read_only_fields = ['id']

    def get_read_ids(self, obj):
        return eval(obj.read_ids)

    def create(self, validated_data):
        notice = Notice.objects.all().order_by('-sort_id').first()
        if notice:
            validated_data['sort_id'] = notice.sort_id + 1
        return super().create(validated_data)


class NoticeUpdateSerializer(CustomModelSerializer):
    """
    系统公告更新-序列化器
    """

    read_ids = serializers.ListField(required=False)

    class Meta:
        model = Notice
        fields = '__all__'


class NavSerializer(CustomModelSerializer):
    """
    便捷导航-序列化器
    """

    links = serializers.SerializerMethodField()

    class Meta:
        model = Navigation
        fields = '__all__'
        read_only_fields = ['id']

    def get_links(self, obj):
        return eval(obj.links)


class NavCreateUpdateSerializer(CustomModelSerializer):
    """
    便捷导航创建-序列化器
    """

    links = serializers.JSONField()

    class Meta:
        model = Navigation
        fields = '__all__'

    def create(self, validated_data):
        navigation = Navigation.objects.all().order_by('-sort_id').first()
        if navigation:
            validated_data['sort_id'] = navigation.sort_id + 1
        return super().create(validated_data)
